<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

import {
  createStatusSubscription,
  deleteStatusSubscription,
  getResourceStatusSubscriptions,
} from '#/api/resource-center/custom-status-api';

// Props
interface Props {
  resourceId?: string;
}

const props = defineProps<Props>();

// 响应式数据
const loading = ref(false);
const showCreateModal = ref(false);
const showTestModal = ref(false);
const subscriptions = ref<any[]>([]);
const testResult = ref({
  success: false,
  message: '',
  details: null,
});

// 表单数据
const formRef = ref();
const formData = reactive({
  subscriptionType: 'resource',
  resourceId: '',
  resourceType: '',
  statusTypes: [] as string[],
  events: [] as string[],
  callbackUrl: '',
  description: '',
});

// 表单验证规则
const rules = {
  statusTypes: [{ required: true, message: '请选择状态类型' }],
  events: [{ required: true, message: '请选择事件类型' }],
  callbackUrl: [{ required: true, message: '请输入回调URL' }],
  resourceId: [{ required: true, message: '请输入资源ID' }],
  resourceType: [{ required: true, message: '请选择资源类型' }],
};

// 表格列定义
const columns = [
  { title: '订阅类型', dataIndex: 'subscriptionType', key: 'subscriptionType' },
  { title: '目标', dataIndex: 'target', key: 'target' },
  { title: '状态类型', key: 'statusTypes' },
  { title: '事件类型', key: 'events' },
  { title: '回调URL', dataIndex: 'callbackUrl', key: 'callbackUrl' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '操作', key: 'action', width: 120 },
];

// 方法
const loadSubscriptions = async () => {
  if (!props.resourceId) return;

  loading.value = true;
  try {
    const response = await getResourceStatusSubscriptions(props.resourceId);
    subscriptions.value = response.data || [];
  } catch {
    message.error('加载订阅列表失败');
  } finally {
    loading.value = false;
  }
};

const saveSubscription = async () => {
  try {
    await formRef.value.validate();

    const subscription = {
      resourceId:
        formData.subscriptionType === 'resource'
          ? formData.resourceId
          : undefined,
      resourceType:
        formData.subscriptionType === 'resourceType'
          ? formData.resourceType
          : undefined,
      statusTypes: formData.statusTypes,
      events: formData.events,
      callbackUrl: formData.callbackUrl,
      description: formData.description,
    };

    await createStatusSubscription(subscription);
    message.success('订阅创建成功');
    showCreateModal.value = false;
    resetForm();
    loadSubscriptions();
  } catch {
    message.error('创建订阅失败');
  }
};

const deleteSubscription = async (id: string) => {
  try {
    await deleteStatusSubscription(id);
    message.success('删除成功');
    loadSubscriptions();
  } catch {
    message.error('删除失败');
  }
};

const testSubscription = async (subscription: any) => {
  try {
    // 模拟测试订阅
    testResult.value = {
      success: Math.random() > 0.3, // 70%成功率
      message: Math.random() > 0.3 ? '回调URL响应正常' : '回调URL无响应',
      details: {
        subscriptionId: subscription.id,
        testTime: new Date().toISOString(),
        responseTime: Math.floor(Math.random() * 1000) + 100,
        statusCode: Math.random() > 0.3 ? 200 : 500,
      },
    };
    showTestModal.value = true;
  } catch {
    message.error('测试失败');
  }
};

const resetForm = () => {
  formRef.value?.resetFields();
  Object.assign(formData, {
    subscriptionType: 'resource',
    resourceId: '',
    resourceType: '',
    statusTypes: [],
    events: [],
    callbackUrl: '',
    description: '',
  });
};

// 生命周期
onMounted(() => {
  loadSubscriptions();
});
</script>

<template>
  <div class="status-subscription-manager">
    <a-card title="状态订阅管理" :bordered="false">
      <template #extra>
        <a-button type="primary" @click="showCreateModal = true">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          新建订阅
        </a-button>
      </template>

      <!-- 订阅列表 -->
      <a-table
        :columns="columns"
        :data-source="subscriptions"
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'statusTypes'">
            <a-space>
              <a-tag
                v-for="type in record.statusTypes"
                :key="type"
                color="blue"
              >
                {{ type }}
              </a-tag>
            </a-space>
          </template>
          <template v-else-if="column.key === 'events'">
            <a-space>
              <a-tag v-for="event in record.events" :key="event" color="green">
                {{ event }}
              </a-tag>
            </a-space>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="testSubscription(record)"
              >
                测试
              </a-button>
              <a-popconfirm
                title="确定要删除这个订阅吗？"
                @confirm="deleteSubscription(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建订阅模态框 -->
    <a-modal
      :open="showCreateModal"
      title="新建状态订阅"
      @ok="saveSubscription"
      @cancel="showCreateModal = false"
    >
      <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
        <a-form-item label="订阅类型" name="subscriptionType">
          <a-radio-group v-model:value="formData.subscriptionType">
            <a-radio value="resource">指定资源</a-radio>
            <a-radio value="resourceType">资源类型</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="formData.subscriptionType === 'resource'"
          label="资源ID"
          name="resourceId"
        >
          <a-input
            v-model:value="formData.resourceId"
            placeholder="请输入资源ID"
          />
        </a-form-item>

        <a-form-item
          v-if="formData.subscriptionType === 'resourceType'"
          label="资源类型"
          name="resourceType"
        >
          <a-select
            v-model:value="formData.resourceType"
            placeholder="选择资源类型"
          >
            <a-select-option value="hotel">酒店</a-select-option>
            <a-select-option value="room">房间</a-select-option>
            <a-select-option value="order">订单</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="状态类型" name="statusTypes">
          <a-checkbox-group v-model:value="formData.statusTypes">
            <a-checkbox value="LIFECYCLE">生命周期状态</a-checkbox>
            <a-checkbox value="AVAILABILITY">可用性状态</a-checkbox>
            <a-checkbox value="VERSION">版本状态</a-checkbox>
            <a-checkbox value="CUSTOM">自定义状态</a-checkbox>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="事件类型" name="events">
          <a-checkbox-group v-model:value="formData.events">
            <a-checkbox value="STATUS_CHANGED">状态变更</a-checkbox>
            <a-checkbox value="LIFECYCLE_CHANGED">生命周期变更</a-checkbox>
            <a-checkbox value="AVAILABILITY_CHANGED">可用性变更</a-checkbox>
            <a-checkbox value="VERSION_CHANGED">版本变更</a-checkbox>
            <a-checkbox value="CUSTOM_STATUS_CHANGED">
              自定义状态变更
            </a-checkbox>
            <a-checkbox value="BEHAVIOR_EXECUTED">行为执行</a-checkbox>
            <a-checkbox value="COMPENSATION_TRIGGERED">补偿触发</a-checkbox>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="回调URL" name="callbackUrl">
          <a-input
            v-model:value="formData.callbackUrl"
            placeholder="https://example.com/webhook"
          />
        </a-form-item>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入订阅描述"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 测试结果模态框 -->
    <a-modal
      :open="showTestModal"
      title="订阅测试结果"
      @cancel="showTestModal = false"
    >
      <div class="test-result">
        <a-result
          :status="testResult.success ? 'success' : 'error'"
          :title="testResult.success ? '测试成功' : '测试失败'"
          :sub-title="testResult.message"
        >
          <template #extra>
            <a-button type="primary" @click="showTestModal = false">
              确定
            </a-button>
          </template>
        </a-result>

        <div v-if="testResult.details" class="test-details">
          <h4>详细信息：</h4>
          <pre>{{ JSON.stringify(testResult.details, null, 2) }}</pre>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.status-subscription-manager {
  .test-result {
    .test-details {
      margin-top: 16px;
      padding: 16px;
      background: #f5f5f5;
      border-radius: 4px;

      h4 {
        margin-bottom: 8px;
      }

      pre {
        margin: 0;
        font-size: 12px;
        color: #666;
      }
    }
  }
}
</style>
